﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ResourceServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {

        private readonly ILogger<ValuesController> _logger;
        /// <summary>
        /// The schemes
        /// </summary>
        protected readonly IAuthenticationSchemeProvider Schemes;

        /// <summary>
        /// The handlers
        /// </summary>
        protected readonly IAuthenticationHandlerProvider Handlers;
        private readonly IOptions<AuthenticationOptions> _authOptions;

        public ValuesController(
            IAuthenticationSchemeProvider schemes,
            IAuthenticationHandlerProvider handlers,
            IOptions<AuthenticationOptions> options,
            ILogger<ValuesController> logger)
        {

            _logger = logger;

            _authOptions = options;
            Schemes = schemes;
            Handlers = handlers;
        }

        // async Task<IActionResult>
        // GET api/values
        [HttpGet]
        //public ActionResult<IEnumerable<string>> Get()
        public async Task<ActionResult<IEnumerable<string>>> GetAsync()
        {

            // ===================================
            var opt = _authOptions;
            var defaultScheme = await Schemes.GetDefaultAuthenticateSchemeAsync();
            var s2 = await Schemes.GetDefaultChallengeSchemeAsync();
            var s3 = await Schemes.GetDefaultSignInSchemeAsync();
            var handler = await Handlers.GetHandlerAsync(HttpContext, defaultScheme.Name);
            var result2 = await handler.AuthenticateAsync();

            foreach(var scheme in await Schemes.GetAllSchemesAsync())
            {
                _logger.Log(LogLevel.Information, $"Scheme: {scheme.Name}, Handler: {scheme.HandlerType.FullName}");
            }
            // ===================================

            return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
            //return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
